package com.kpx.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kpx.app.R;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.MD5Util;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.dbutils.SpUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;
import com.kpx.app.wigdet.ClearEditText;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by congdy on 17/3/1.
 * 重置密码
 */

public class ActivityResetPwd extends ActivityBase {
    @BindView(R.id.img_arrow)
    ImageView img_arrow;
    @BindView(R.id.titleview)
    TitleView titleview;
    @BindView(R.id.txt_step1)
    TextView txtStep1;
    @BindView(R.id.txt_step2)
    TextView txtStep2;
    @BindView(R.id.cet_phone_num)
    ClearEditText cetPhoneNum;
    @BindView(R.id.cet_code)
    ClearEditText cetCode;
    @BindView(R.id.btn_code)
    Button btnCode;
    @BindView(R.id.ll_step1)
    LinearLayout llStep1;
    @BindView(R.id.rl_step2)
    RelativeLayout rl_step2;
    @BindView(R.id.cet_set_pwd)
    ClearEditText cetSetPwd;
    @BindView(R.id.btn_reset)
    Button btnReset;
    private int type = 0;
    public static int intype = 0;
    private int time = 120;

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_reset_pwd);
        ButterKnife.bind(this);
        UIUtils.setTitle(titleview, "重置密码");
        titleview.setLeftIconRes(R.drawable.arrow_black);
        if(intype==2){
            cetPhoneNum.setText(UserInfoUtils.getCachedLoginUser().getUSER().getPhone());
            cetPhoneNum.setEnabled(false);
            cetPhoneNum.setClearIconVisible(false);
        }
    }

    @Override
    public void initData() {

    }


    @Override
    protected void onResume() {
        super.onResume();
        long lasttime = SpUtil.getLong(intype==3?Constants.TIME_CODE_3:Constants.TIME_CODE_2);
        if(lasttime!=0&&System.currentTimeMillis()-lasttime<120*1000){
            btnCode.setEnabled(false);
            time = (int)((120*1000-System.currentTimeMillis()+lasttime)/1000);
            handler.sendEmptyMessage(0);
            type=0;
        }
    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

    @OnClick({R.id.btn_code, R.id.btn_reset})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_code:
                if (TextUtils.isEmpty(cetPhoneNum.getText().toString().trim())) {
                    ToastUtil.getInstance().showToast(ActivityResetPwd.this, "请输入手机号码");
                    return;
                }
                time = 120;
                getCode();
                break;
            case R.id.btn_reset:
                if (checkedData()) {
                    if (!TextUtils.isEmpty(cetPhoneNum.getText().toString().trim())
                            && !TextUtils.isEmpty(cetCode.getText().toString().trim())
                            && TextUtils.isEmpty(cetSetPwd.getText().toString().trim())) {
                        toCheckNet();
                        return;
                    }
                    if (type == 1 && TextUtils.isEmpty(cetSetPwd.getText().toString().trim())) {
                        ToastUtil.getInstance().showToast(ActivityResetPwd.this, "请输入密码");
                        return;
                    }
                    doReset();
                }
                break;
        }
    }

    private void toCheckNet() {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("phone", cetPhoneNum.getText().toString().trim());
        map.put("authCode", cetCode.getText().toString().trim());
        map.put("type", intype==3?"2":"1");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    type = 1;
                    setType(type);
                } else {
                    ToastUtil.getInstance().showToast(ActivityResetPwd.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityResetPwd.this, error);
            }

        }, null, null).POST(intype==2?HttpDataReqUrl.URL_POST_CHECK_CODE_1:HttpDataReqUrl.URL_POST_CHECK_CODE_2, intype==3?false:true, map);
    }

    private boolean checkedData() {
        if (type == 0 && TextUtils.isEmpty(cetPhoneNum.getText().toString().trim())) {
            ToastUtil.getInstance().showToast(ActivityResetPwd.this, "请输入手机号码");
            return false;
        }
        if (type == 0 && TextUtils.isEmpty(cetCode.getText().toString().trim())) {
            ToastUtil.getInstance().showToast(ActivityResetPwd.this, "请输入验证码");
            return false;
        }
        return true;
    }

    private void setType(int showtype) {
        txtStep2.setTextColor(getResources().getColor(showtype == 0 ? R.color.grey_b3 : R.color.red_FF4881));
        img_arrow.setBackgroundResource(showtype == 0 ? R.drawable.arrow : R.drawable.arrow_red_right);
        rl_step2.setVisibility(showtype == 0 ? View.GONE : View.VISIBLE);
        llStep1.setVisibility(showtype == 0 ? View.VISIBLE : View.GONE);
        btnReset.setText(showtype == 0 ? "验证" : "确定");
    }

    /**
     * 参数：phone手机号,authCode验证码,pwd密码
     * 返回：{"code":0}
     */
    private void doReset() {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("phone", cetPhoneNum.getText().toString().trim());
        map.put("authCode", cetCode.getText().toString().trim());
        map.put("pwd", MD5Util.encrypt(cetSetPwd.getText().toString().trim()));
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    finish();
                    SpUtil.putString(Constants.KEY_USER_PHONE, cetPhoneNum.getText().toString().trim());
                    SpUtil.putString(Constants.KEY_USER_PWD, cetSetPwd.getText().toString().trim());
                    ToastUtil.getInstance().showToast(ActivityResetPwd.this, "修改成功");
                } else {
//                    type = 0;
//                    setType(type);
                    ToastUtil.getInstance().showToast(ActivityResetPwd.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityResetPwd.this, error);
            }

        }, null, null).POST(intype==3?HttpDataReqUrl.URL_POST_FORGET_PWD:HttpDataReqUrl.URL_POST_RESET_PWD, true, map);
    }

    @Override
    public void onBackPressed() {
//        if (type == 1) {
//            type = 0;
//            setType(type);
//        }else{
        super.onBackPressed();
//        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            time--;
            if (time <= 0) {
                btnCode.setEnabled(true);
                btnCode.setText("获取验证码");
            } else {
                btnCode.setText(time + "s");
                handler.sendEmptyMessageDelayed(0, 1000);
            }
        }
    };

    /**
     * 获取验证码
     * valid 1：是，2非
     */
    private void getCode() {
        showLoadingDialog();
        UserInfoUtils.getCode(ActivityResetPwd.this, cetPhoneNum.getText().toString().trim(), intype, new UserInfoUtils.OnGetCodeBackListener() {
            @Override
            public void back(boolean s) {
                dissmissLoadingDialog();
                if (s) {
                    time = 120;
                    btnCode.setEnabled(false);
                    handler.sendEmptyMessage(0);
                    ToastUtil.getInstance().showToast(ActivityResetPwd.this, "获取成功");
                    SpUtil.putLong(intype==3?Constants.TIME_CODE_3:Constants.TIME_CODE_2,System.currentTimeMillis());
                }
            }
        });
    }
}
